<script setup lang="ts">
import {ref, watch} from "vue";
import {logout} from "@/api/user";
import {useUserInfoStore} from "@/stores/user_info";
import {update} from "@/api/user";
import {ElMessage} from 'element-plus'
import {useRouter} from "vue-router";

// 获取用户信息
const userInfoStore = useUserInfoStore()
userInfoStore.selectUserInfo()

const router = useRouter()
const info = userInfoStore.userInfo
const userInfo: any = ref({
  nickname: '',
  email: ''
})
watch(() => userInfoStore.userInfo, (newVal) => {
  userInfo.value = newVal
})
userInfo.value.nickname = info.nickname as String
// 退出登录
const toLogout = () => {
  logout().then((res: any) => {
    userInfoStore.userInfo = {}
    userInfoStore.token = ''
    router.replace('/login')
  })
}
// 修改昵称
let showMod = ref(false)
const result = async (res: boolean) => {
  if (res) {
    if (userInfo.value.nickname.trim()) {
      await update(userInfo.value).then((res) => {
        userInfoStore.updateUserInfo()
      })
      showMod.value = false
    } else {
      ElMessage({
        grouping: true,
        message: '昵称不能为空',
        type: 'error',
        duration: 1500,
        plain: true,
      })
    }
  } else {
    showMod.value = false
  }
}
</script>

<template>
  <div>
    <div class="userinfo">
      <div class="userinfo-item">
        <div>
          <p class="text-1">账号ID</p>
          <p class="text-2">{{ info.email }}</p>
        </div>
      </div>
      <el-divider/>
      <div class="userinfo-item">
        <div>
          <p class="text-1">修改昵称</p>
          <p class="text-2">{{ userInfo.nickname || "修改您展示的昵称" }}</p>
        </div>
        <p class="text-3" @click="showMod = true">修改</p>
      </div>
      <el-divider/>
    </div>
    <div class="btn-box">
      <el-button size="large" type="danger" @click="toLogout()" round>退出登录</el-button>
    </div>
    <my-dialog :showMod="showMod" @result="result" :title="'修改昵称'">
      <div style="padding: 20px">
        <el-input v-model="userInfo.nickname" placeholder="输入修改昵称"/>
      </div>
    </my-dialog>
  </div>
</template>

<style scoped lang="scss">
.userinfo {
  padding-top: 25px;
  margin: 0 15px;

  .userinfo-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 80%;

    .text-1 {
      font-size: 14px;
      font-weight: 800;
      color: #333;
      margin-bottom: 10px;
    }

    .text-2 {
      font-size: 14px;
      color: #666;
    }

    .text-3 {
      cursor: pointer;
      color: #2f8de1;
    }

  }

}

.btn-box {
  display: flex;
  justify-content: center;
  margin: 0 15px;
}
</style>